<?php

	require_once('../includes/googleApi.php');
	require_once('../includes/provider-account.php');

	$_callback = $_REQUEST['callback'];
	$_action = $_REQUEST['act'];

	// init
	$result = TRUE;

	if (isset($_action))
	{
		switch ($_action) 
		{
			case 'logout': /* destroy session */
				session_destroy();
			break;
			case 'qls': /* query for login status */
				$data['g_access_token'] = $_SESSION['g_access_token'];
				$data['g_token_type'] = $_SESSION['g_token_type'];
				$data['g_expires_in'] = $_SESSION['g_expires_in'];
				$data['g_id_token'] = $_SESSION['g_id_token'];
				$data['g_refresh_token'] = $_SESSION['g_refresh_token'];
				$data['uid'] = $_SESSION['uid'];
				$data['SESSION_ID'] = session_id ();

				// cached?
				if (isset($_SESSION['me']) && $_SESSION['me'] != NULL) {
					$data['me'] = unserialize($_SESSION['me']);
				} else {
					/* check g_id_token against db for Name + uid */
					$p = new AccountProvider();
					$r = $p->get($data['uid']);
					if (empty($r)) {
						/* unexpected case */
						$result = FALSE;
						$err = 'unexpected case unmatched google UID.';
						break;
					} else {
						$data['me'] = $r[$_SESSION['uid']];
						$_SESSION['me'] = serialize($data['me']);
					}
				}
			break;
			case 'gapi': /* call google api */
				$api_name = $_REQUEST['api_name'];
				$data = callGoogleApi($api_name, $_REQUEST, &$result, &$err);
			break;
			default:
				$err = 'unknown \'act\' value: '.$_action;
				$result = FALSE;
			break;
		}
	}
	else
	{
		$err = 'undefined \'act\' value';
		$result = FALSE;
	}

	// enclosure
	echo $_callback.'('.json_encode(array(
			'result' => $result,
			'data' => $data,
			'err' => $err
		)).');';
?>
